package com.yanxin.workflow;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;

public class DomUtils {

    private static final Log logger = LogFactory.getLog(DomUtils.class);
    /**
     * w3c document covert to xml string
     *
     * @param doc document
     * @return xml
     */
    public static String docToXmlStr(Document doc) {

        DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = null;
        try {
            transformer = tf.newTransformer();
            transformer.transform(domSource, result);
        } catch (TransformerException e) {
            logger.error("document covert to xml failed");
            e.printStackTrace();
        }
        return writer.toString();
    }
}
